package com.demo.ohos_zblibrary.slice;

import com.demo.ohos_zblibrary.ResourceTable;
import com.demo.ohos_zblibrary.tool.IntentUtil;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import zuo.biao.library.util.Log;
import zuo.biao.library.util.thread.pool.ThreadPoolProxyFactory;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 线程示例
 */
public class ThreadPoolAbilitySlice extends AbilitySlice {
    private static final String TAG = "ThreadPoolAbilitySlice";

    private static final int DEFAULT_POOL = 500;
    private static final int CACHE_POOL = 800;
    private static final int SINGLE_POOL = 1000;

    DirectionalLayout dlMain;
    DirectionalLayout dlMsg;
    DirectionalLayout dlFind;
    DirectionalLayout dlSetting;

    Text txt_title;
    Text txt_main;
    Text txt_msg;
    Text txt_find;
    Text txt_setting;
    Text txt_center;

    Button btn_one;
    Button btn_tow;
    Button btn_three;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_home_layout);

        initTopAndBottomView();
    }

    private void initTopAndBottomView() {
        txt_title = (Text) findComponentById(ResourceTable.Id_txt_title);
        txt_main = (Text) findComponentById(ResourceTable.Id_txt_main);
        txt_msg = (Text) findComponentById(ResourceTable.Id_txt_msg);
        txt_find = (Text) findComponentById(ResourceTable.Id_txt_find);
        txt_setting = (Text) findComponentById(ResourceTable.Id_txt_setting);
        txt_center = (Text) findComponentById(ResourceTable.Id_txt_center);
        dlMain = (DirectionalLayout) findComponentById(ResourceTable.Id_dl_main);
        dlMsg = (DirectionalLayout) findComponentById(ResourceTable.Id_dl_msg);
        dlFind = (DirectionalLayout) findComponentById(ResourceTable.Id_dl_find);
        dlSetting = (DirectionalLayout) findComponentById(ResourceTable.Id_dl_setting);
        btn_one = (Button) findComponentById(ResourceTable.Id_btn_one);
        btn_tow = (Button) findComponentById(ResourceTable.Id_btn_tow);
        btn_three = (Button) findComponentById(ResourceTable.Id_btn_three);

        txt_title.setText("消息");
        txt_msg.setTextColor(Color.BLUE);
        dlMain.setClickedListener(component -> showMain());
        dlMsg.setClickedListener(component -> showMsg());
        dlFind.setClickedListener(component -> showFind());
        dlSetting.setClickedListener(component -> showSetting());

        btn_one.setClickedListener(component -> defaultPool());
        btn_tow.setClickedListener(component -> cachePool());
        btn_three.setClickedListener(component -> singlePool());
    }

    private EventHandler eventHandler =
            new EventHandler(EventRunner.getMainEventRunner()) {
                @Override
                protected void processEvent(InnerEvent event) {
                    super.processEvent(event);
                    switch (event.eventId) {
                        case DEFAULT_POOL:
                            handleMsgFromDefault();
                            break;
                        case CACHE_POOL:
                            handleMsgFromCache();
                            break;
                        case SINGLE_POOL:
                            handleMsgFromSingle();
                            break;
                    }
                }
            };

    /**
     * 常规线程池：
     * 一般异步任务或与ui有关的建议使用此线程池
     **/
    private void defaultPool() {
        ThreadPoolProxyFactory.getDefaultThreadPool()
                .execute(
                        new Runnable() {
                            @Override
                            public void run() {
                                InnerEvent event = InnerEvent.get(DEFAULT_POOL);
                                eventHandler.sendEvent(event, 500);
                            }
                        });
    }

    /*
     * cache线程池：
     * 建议与ui无关的异步任务使用此线程池
     * #与UI有关的，注意处理好数据处理顺序。
     *
     * 这里仅在log输出展示
     * */
    private int count = 1;

    private void cachePool() {
        for (int j = 0; j < 20; j++) {
            ThreadPoolProxyFactory.getCacheThreadPool()
                    .execute(
                            new Runnable() {
                                @Override
                                public void run() {
                                    InnerEvent event = InnerEvent.get(CACHE_POOL);
                                    eventHandler.sendEvent(event, 500);
                                }
                            });
        }
    }

    /*
     * 单一线程池
     * 适合需要顺序执行的异步任务
     *
     *
     * */
    private AtomicInteger taskIndex = new AtomicInteger();

    private void singlePool() {
        taskIndex.set(1);
        for (int i = 0; i < 5; i++) {
            ThreadPoolProxyFactory.getSingleThreadPool()
                    .execute(
                            new Runnable() {
                                @Override
                                public void run() {
                                    InnerEvent event = InnerEvent.get(SINGLE_POOL);
                                    eventHandler.sendEvent(event, 1000);
                                    try {
                                        Thread.sleep(1000);
                                    } catch (InterruptedException e) {
                                        Log.error("InterruptedException",e.getMessage());
                                    }
                                }
                            });
        }
    }

    private void handleMsgFromDefault() {
        txt_center.setText("DefaultThreadPool; 核心3线程，最大5线程，3000毫秒存活时间可执行一般异步任务需求。\n使用简单，这里仅做简单展示");
    }

    String info =
            "CacheThreadPool: 线程数为Integer.MAX,无核心线程，存活时间："
                    + "60毫秒适合执行大量、高频、一次性、后台（建议无关UI的）等的异步任务，n"
                    + "仅做简单展示，输出可查看LOGn";

    StringBuffer sb = new StringBuffer();

    private void handleMsgFromCache() {
        sb.append(info);
        txt_center.setText(sb.toString());
    }

    StringBuffer singleSB = new StringBuffer();

    private void handleMsgFromSingle() {
        singleSB.append("正在处理任务： " + taskIndex.getAndIncrement() );
        txt_center.setText(singleSB.toString());
    }

    private void showMain() {
        IntentUtil.toSlice(this, IntentUtil.MAINSLICE);
    }

    private void showMsg() {
    }

    private void showFind() {
        IntentUtil.toSlice(this, IntentUtil.PAGESLIDERABILITYSLICE);
    }

    private void showSetting() {
        IntentUtil.toSlice(this, IntentUtil.SETTINGSLICE);
    }
}
